const fs = require('fs');
const path = require('path');

/**
 * @param {Egg.Application} app - egg application
 */
module.exports = app => {
  const { router, controller, io } = app;

  /**
   * webSocket
   */
  const nsp = io.of('/');
  nsp.route('server', io.controller.index.ping);
  nsp.route('ack', io.controller.index.ack);
  
  // 首页路由
  router.get('/', controller.home.index);

  // 自动加载所有模块路由
  const routerDir = path.join(__dirname, 'router');

  if (fs.existsSync(routerDir)) {
    fs.readdirSync(routerDir).forEach(file => {
      if (file.endsWith('.js')) {
        try {
          const routerModule = require(path.join(routerDir, file));
          if (typeof routerModule === 'function') {
            routerModule(app);
          }
        } catch (error) {
          console.error(`Error loading router module ${file}:`, error);
        }
      }
    });
  }
};
